﻿using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace Web.HelperClasses
{
    public static class OAuth
    {
        private static string _token;
        private static DateTime _ending;

        public static string OAuthToken
        {
            get
            {
                if (String.IsNullOrEmpty(_token) || DateTime.Now >= _ending)
                    GetOAuthToken();
                return _token;
            }
        }

        private static void GetOAuthToken()
        {
            string postData = "grant_type=password"
            + "&client_id=9ee74d9532bf41c9a04bb2ffe65ccaa1"
			+ "&username=" + ConfigurationManager.AppSettings["YandexFotkiUsername"]
            + "&password=" + ConfigurationManager.AppSettings["YandexFotkiPassword"];
            byte[] data = Encoding.ASCII.GetBytes(postData);

            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("https://oauth.yandex.ru/token");
            myRequest.Method = "POST";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.ContentLength = data.Length;
            Stream newStream = myRequest.GetRequestStream();

            newStream.Write(data, 0, data.Length);
            newStream.Close();

            var myToken = new StreamReader(myRequest.GetResponse().GetResponseStream()).ReadToEnd();
			var tokenMatch = (new Regex("\"access_token\": \"(?<token>[^\"]+)\"")).Match(myToken);
			var expirationTimeMatch = (new Regex("\"expires_in\": (?<expires_in>\\d+)")).Match(myToken);
        	var tokenTypeMatch = (new Regex("\"token_type\": (?<token_type>\\w+)")).Match(myToken);
            if (!tokenMatch.Success)
                throw new ArgumentException();

            _token = tokenMatch.Groups["token"].Value;
            if (expirationTimeMatch.Success)
                //если в ответе есть информация об истечении срока жизни токена
                _ending = DateTime.Now.AddSeconds(Double.Parse(expirationTimeMatch.Groups["expires_in"].Value));
            else
                //если токен вечный
                _ending = DateTime.MaxValue;
        }
    }
}